package com.pig4cloud.pigx.strategy.config.thread;

import com.pig4cloud.pigx.common.customize.thread.handler.CommonRejectedExecutionHandler;
import com.pig4cloud.pigx.strategy.config.strategy.ContractScheduledConfig;
import com.pig4cloud.pigx.strategy.config.strategy.ContractWebsocketConfig;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

/**
 * 线程池配置
 *
 * @since 2022/9/27 19:31
 */
@Configuration
@AllArgsConstructor
public class ThreadPoolConfig {
    private final ContractWebsocketConfig contractWebsocketConfig;
    private final ContractScheduledConfig contractScheduledConfig;

    /**
     * websocket线程池配置
     *
     * @return {@link ThreadPoolTaskExecutor}
     * @since 2022/9/27 19:42
     */
    @Bean
    public ThreadPoolTaskExecutor websocketThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setMaxPoolSize(contractWebsocketConfig.getMaxPoolSize());
        executor.setCorePoolSize(contractWebsocketConfig.getCorePoolSize());
        executor.setQueueCapacity(contractWebsocketConfig.getQueueCapacity());
        executor.setKeepAliveSeconds(contractWebsocketConfig.getKeepAliveSeconds());
        // 设置处理策略
        executor.setRejectedExecutionHandler(new CommonRejectedExecutionHandler());
        executor.setThreadNamePrefix(contractWebsocketConfig.getThreadNamePrefix());
        return executor;
    }

    /**
     * 定时任务线程池
     *
     * @return {@link TaskScheduler}
     * @since 2022/9/27 20:34
     */
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
        executor.setPoolSize(contractScheduledConfig.getCorePoolSize());
        executor.setThreadNamePrefix(contractScheduledConfig.getThreadNamePrefix());
        executor.setRejectedExecutionHandler(new CommonRejectedExecutionHandler());
        executor.initialize();
        return executor;
    }
}
